<script setup lang="ts">
const props = withDefaults(defineProps<{
  total?: number,
  page?: number,
  pageSize?: number
}>(), {
  total: 0,
  page: 1,
  pageSize: 9
});

const { page, total, pageSize } = toRefs(props);

const range = ref(4);
const maxShowPageBlocks = 9;
const maxPage = computed(() => Math.ceil(total.value / pageSize.value));
const totalPage = computed(() => Math.min(maxShowPageBlocks, maxPage.value));
const emits = defineEmits<{
  (event: 'onChange', value: number): void
}>();

const pageInput = ref('');
const turnByPage = (page?: number) => {
  emits('onChange', page || Number(pageInput.value));
};
const getPageNumber = (idx: number) => {
  const current = idx + page.value;
  if (page.value + range.value <= totalPage.value) {
    return idx + 1;
  }
  if (page.value + range.value > maxPage.value) {
    return maxPage.value - totalPage.value + idx + 1;
  }
  return current - range.value;
};
</script>

<template>
  <div class="py-4 flex justify-end gap-2">
    <button
      v-for="(_, idx) in totalPage"
      :key="idx"
      class="text-sm rounded-sm w-8 h-8 flex justify-center items-center shadow-md shadow-neutral-850 border border-neutral-600 cursor-pointer"
      :class="[page === getPageNumber(idx) ? 'bg-amber-600' : 'bg-neutral-950']"
      @click="turnByPage(getPageNumber(idx))"
    >{{ getPageNumber(idx) }}</button>
    <input
      v-model="pageInput"
      class="w-12 y-8 text-sm text-neutral-800 text-center border-1 border-neutral-600 rounded-sm focus:border-neutral-600 outline:none"
      @keydown.enter="() => turnByPage()"
    >
  </div>
</template>

<style lang="scss" scoped>
</style>